{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "7f33dd7f",
   "metadata": {},
   "source": [
    "# Parse /results/"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "aed0f90e",
   "metadata": {},
   "outputs": [],
   "source": [
    "# only works for using NPSR as the algorithm\n",
    "\n",
    "import os\n",
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "\n",
    "print('Datasets in /results/ -', os.listdir('results'))\n",
    "\n",
    "res = {}\n",
    "for dset in os.listdir('results'):\n",
    "    res[dset] = {}\n",
    "    for algo in os.listdir('results/' + dset):\n",
    "        assert algo == 'NPSR'\n",
    "        res[dset][algo] = []\n",
    "        print(f'Dataset: {dset}, Algorithm: {algo}')\n",
    "        num_res_files = np.sum(['_result.txt' in file for file in os.listdir(f'results/{dset}/{algo}')])\n",
    "        if num_res_files >= 1:\n",
    "            print(f'  Found {num_res_files} result files.')\n",
    "        else:\n",
    "            print('  Found no result files. Skipping directory.')\n",
    "            continue\n",
    "        \n",
    "        for fname in os.listdir(f'results/{dset}/{algo}'):\n",
    "            if '_result.txt' not in fname:\n",
    "                continue\n",
    "            res_ent = {}\n",
    "            res_ent['datetime'] = fname.replace('_result.txt', '')\n",
    "            with open(f'results/{dset}/{algo}/{fname}', 'r') as file:\n",
    "                lines = file.readlines()\n",
    "                lines = [line.replace('\\n','') for line in lines]\n",
    "            res_ent['dset_config'] = lines[0]\n",
    "            res_ent['model_config'] = lines[1]\n",
    "            res_ent['epoch'] = []\n",
    "\n",
    "            epochs = int(res_ent['model_config'].split('epochs=')[-1].split(',')[0])\n",
    "            lines_per_epoch = (len(lines)-2) // epochs\n",
    "            for epoch in range(epochs):\n",
    "                lines_ep = lines[2 + epoch*lines_per_epoch: 2 + (epoch+1)*lines_per_epoch]\n",
    "                assert lines_ep[0] == f'epoch={epoch}'\n",
    "                # only record F1 and AUC\n",
    "                res_ep = {}\n",
    "                res_ep['M_pt_F1'] = float(lines_ep[1].split('F1:')[-1].split(' ')[0])\n",
    "                res_ep['M_pt_AUC'] = float(lines_ep[1].split('AUC:')[-1].split(' ')[0])\n",
    "                res_ep['M_seq_F1'] = float(lines_ep[2].split('F1:')[-1].split(' ')[0])\n",
    "                res_ep['M_seq_AUC'] = float(lines_ep[2].split('AUC:')[-1].split(' ')[0])\n",
    "                res_ep['d'] = {}\n",
    "                for line in lines_ep[3:]:\n",
    "                    d = int(line.split('d ')[1].split(' ')[0])\n",
    "                    res_ep['d'][d] = {}\n",
    "                    tmp = line.split('Soft ')[1].split('  Hard ')\n",
    "                    tmp = [tmp[0]] + tmp[1].split('  Inf ')\n",
    "                    tmp = [[float(x) for x in t.replace('F1:', '').split('  AUC:')] for t in tmp]\n",
    "                    res_ep['d'][d]['Soft F1'] = tmp[0][0]\n",
    "                    res_ep['d'][d]['Soft AUC'] = tmp[0][1]\n",
    "                    res_ep['d'][d]['Hard F1'] = tmp[1][0]\n",
    "                    res_ep['d'][d]['Hard AUC'] = tmp[1][1]\n",
    "                    res_ep['d'][d]['Inf F1'] = tmp[2][0]\n",
    "                    res_ep['d'][d]['Inf AUC'] = tmp[2][1]\n",
    "                res_ent['epoch'].append(res_ep)\n",
    "\n",
    "            res[dset][algo].append(res_ent)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "51c0da21",
   "metadata": {
    "scrolled": false
   },
   "outputs": [],
   "source": [
    "for dset in res.keys():\n",
    "    for algo in res[dset].keys():\n",
    "        if len(res[dset][algo]) == 1: # only plot dset + algos with only one result file\n",
    "            res_ent = res[dset][algo][0]\n",
    "            print(dset, algo, res_ent['datetime'])\n",
    "            \n",
    "            print(f'  {res_ent[\"dset_config\"]}')\n",
    "            print(f'  {res_ent[\"model_config\"]}')\n",
    "            \n",
    "            plt.figure()\n",
    "            # select which model + metrics to plot\n",
    "            for plt_name in ['M_pt_F1', 'M_pt_AUC', 'M_seq_F1', 'M_seq_AUC']:\n",
    "                if 'AUC' in plt_name:\n",
    "                    continue\n",
    "                model_metric = [ep[plt_name] for ep in res_ent['epoch']]\n",
    "                plt.plot(np.arange(len(res_ent['epoch'])), model_metric, label=plt_name)\n",
    "            plt.legend()\n",
    "            plt.xlabel('epoch')\n",
    "            plt.ylabel('metric value')\n",
    "            plt.title(f'{dset} - {algo} - {res_ent[\"datetime\"]}')\n",
    "            \n",
    "            ds = res_ent['epoch'][0]['d'].keys()\n",
    "            for d in ds:\n",
    "                plt.figure()\n",
    "                # select which [Soft, Hard, Inf] + metrics to plot\n",
    "                for plt_name in ['Soft F1', 'Soft AUC', 'Hard F1', 'Hard AUC', 'Inf F1', 'Inf AUC']:\n",
    "                    if 'AUC' in plt_name:\n",
    "                        continue\n",
    "                    model_metric = [ep['d'][d][plt_name] for ep in res_ent['epoch']]\n",
    "                    plt.plot(np.arange(len(res_ent['epoch'])), model_metric, label=plt_name)\n",
    "                plt.legend()\n",
    "                plt.xlabel('epoch')\n",
    "                plt.ylabel('metric value')\n",
    "                plt.title(f'{dset} - {algo} - {res_ent[\"datetime\"]} - d={d}')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ef34c0aa",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.16"
  },
  "varInspector": {
   "cols": {
    "lenName": 16,
    "lenType": 16,
    "lenVar": 40
   },
   "kernels_config": {
    "python": {
     "delete_cmd_postfix": "",
     "delete_cmd_prefix": "del ",
     "library": "var_list.py",
     "varRefreshCmd": "print(var_dic_list())"
    },
    "r": {
     "delete_cmd_postfix": ") ",
     "delete_cmd_prefix": "rm(",
     "library": "var_list.r",
     "varRefreshCmd": "cat(var_dic_list()) "
    }
   },
   "types_to_exclude": [
    "module",
    "function",
    "builtin_function_or_method",
    "instance",
    "_Feature"
   ],
   "window_display": false
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
